<?php

/**
 * 获取网卡的MAC地址；目前支持WIN/LINUX系统
 * 
 */
class GetMacAddr
{
    protected $result = array(); // 返回带有MAC地址的字串数组 
    protected $macAddr;

    /**
     * @param string $osType 系统类型:linux,windows
     * 
     */
    public function __construct($osType)
    {
        switch (strtolower($osType)) {
            case "unix":
                break;
            case "solaris":
                break;
            case "aix":
                break;
            case "linux": {
                    $this->for_linux_os();
                }
                break;
            default: {
                    $this->for_windows_os();
                }
                break;
        }
    }

    /**
     * 处理Mac地址
     * @param array
     * @return string
     */
    public function handleMac()
    {
        $temp_array = array();
        foreach ($this->result as $value) {
            if (preg_match(
                "/[0-9a-f][0-9a-f][:-]" . "[0-9a-f][0-9a-f][:-]" . "[0-9a-f][0-9a-f][:-]" . "[0-9a-f][0-9a-f][:-]" . "[0-9a-f][0-9a-f][:-]" . "[0-9a-f][0-9a-f]/i",
                $value,
                $temp_array
            )) {
                $this->macAddr = $temp_array[0];
                break;
            }
        }
        unset($temp_array);
        return $this->macAddr;
    }
    
    /**
     * Linux系统
     */
    protected function for_linux_os()
    {
        @exec("/sbin/ifconfig -a", $this->result);
        return $this->result;
    }
    
    /**
     * windows系统
     */
    protected function for_windows_os()
    {
        @exec("ipconfig /all", $this->result);
        if ($this->result) {
            return $this->result;
        } else {
            $ipconfig = $_SERVER["WINDIR"] . "\system32\ipconfig.exe";
            if (is_file($ipconfig)) {
                @exec($ipconfig . " /all", $this->result);
            } else {
                @exec($_SERVER["WINDIR"] . "\system\ipconfig.exe /all", $this->result);
            }
            return $this->result;
        }
    }
}
